﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    ///客户信息_同步跟单猿
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CustomerInfoToRaipiotController : ControllerBase
    {
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        private readonly ILogger _logger;


        public CustomerInfoToRaipiotController(ILogger<CustomerToGDYRequestDto> logger, IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration, ILoggerFactory loggerFactory)
        {

            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            _logger = loggerFactory.CreateLogger<CustomerInfoToRaipiotController>();

        }

        /// <summary>
        /// 客户信息_同步跟单猿
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostCUSInfoToGDY([FromBody] CustomerToGDYRequestDto strparm)
        {
            string  strMsg = "";
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            List<string> restrSqlList = new List<string>();
            CustomerToGDYResponseDto re = new CustomerToGDYResponseDto();
            Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
            string Operation_type = strparm.Operation_type;


            try
            {
                if (strMsg == "")
                {
                        Dictionary<string, string> urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic = new Dictionary<string, string>(); //查询公用dic
                        urldic.Add("function_description", "跟单猿_Token获取");//查看URL配置表地址描述
                        DataTable token_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                        if (token_dt.Rows.Count > 0)
                        {
                           
                            var reAgv2 = DB.httpGet(token_dt.Rows[0]["interface_url"].ToString(), "", "否");
                            RaipiotTokenResponseDto psp = JsonConvert.DeserializeObject<RaipiotTokenResponseDto>(reAgv2);
                            if (psp.status == 200)
                            {
                                if (Operation_type== "manual")//手工模式传单客户
                                {
                                    CustomerToGDY_RequestDto pus = new CustomerToGDY_RequestDto();
                                    pus.code = strparm.code;
                                    pus.customerName = strparm.customerName;
                                    pus.creditCode = strparm.creditCode;
                                    pus.belong = "CN";
                                    pus.customerType = "RECEIVER";
                                    string jsonText = JsonConvert.SerializeObject(pus);
                                    var reAgv = DB.httpPost("https://ap.gdyape.com/prod-api/facade/customer/addCustomer", jsonText, psp.data.token, "是");
                                    CustomerToGDY_ResponseDto psp2 = JsonConvert.DeserializeObject<CustomerToGDY_ResponseDto>(reAgv);
                                    if (psp2.status != 200)
                                    {
                                        strMsg = psp2.message;
                                    }
                                }
                                else
                                {
                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("customer_code", "");//查询参数
                                    DataTable cus_dt = MethodHelp.GetTableInfo("TMS0054", dic, con);//获取低代码未同步客户清单
                                    if (cus_dt.Rows.Count > 0)
                                    {
                                        foreach (DataRow row in cus_dt.Rows)
                                        {
                                            CustomerToGDY_RequestDto pus = new CustomerToGDY_RequestDto();
                                            pus.code = row["customer_code"].ToString();
                                            pus.customerName = row["customer_name"].ToString();
                                            pus.creditCode = row["tax_code"].ToString();
                                            pus.belong = "CN";
                                            pus.customerType = "RECEIVER";
                                            string jsonText = JsonConvert.SerializeObject(pus);
                                            var reAgv = DB.httpPost("https://ap.gdyape.com/prod-api/facade/customer/addCustomer", jsonText, psp.data.token, "是");
                                            CustomerToGDY_ResponseDto psp2 = JsonConvert.DeserializeObject<CustomerToGDY_ResponseDto>(reAgv);
                                            if (psp2.status != 200)
                                            {
                                                strMsg = strMsg+"-"+psp2.message;
                                            }
                                            else
                                            {
                                                dic = new Dictionary<string, string>(); //查询公用dic
                                                dic.Add("customer_code", row["customer_code"].ToString());
                                                strMsg = MethodHelp.InsertIntoTable("TMS0055", dic, con);//更新记录状态
                                            }
                                        }
                                    }
                                }                               
                            }

                        }                                       
                }
               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }

            _logger.LogInformation(JsonConvert.SerializeObject(re));
            return new JsonResult(re);
        }

      
    }
}
